let gPort = null;
let run = false;
let interval = 1 * 6 * 1000;
let db = DB();

function DB() {
    let db = null;

    async function openDB() {
        return new Promise((resolve, reject) => {
            if (db) {
                resolve(db);
                return;
            }
            var request = indexedDB.open('token');
            request.onerror = function (event) {
                reject(false);
            };
            request.onsuccess = function (event) {
                db = event.target.result;
                resolve(db);
            };
            request.onupgradeneeded = function (event) {
                var db = event.target.result;
                var objectStore = db.createObjectStore("token", { keyPath: "id" });
                objectStore.transaction.oncomplete = function (event) {
                    resolve(db);
                };
            };
        });
    }

    async function getToken() {
        if (!db) db = await openDB();
        var request = db.transaction(["token"]).objectStore("token").get(0);
        return new Promise((resolve, reject) => {
            request.onerror = function (event) {
                resolve(event);
            };
            request.onsuccess = function (event) {
                let token = null;
                if(request.result && request.result.token) token = request.result.token;
                resolve(token);
            };
        });
    }

    async function setToken(val) {
        if (!db) db = await openDB();
        var request = db.transaction(["token"], "readwrite").objectStore("token").put({ id: 0, token: val });
        return new Promise((resolve, reject) => {
            request.onerror = function (event) {
                resolve(event);
            };
            request.onsuccess = function (event) {
                resolve('success');
            };
        });
    }

    return {
        getToken,
        setToken
    };

}

function sleep(time) {
    return new Promise((resolve, reject) => {
        setTimeout(function () {
            resolve(true);
        }, time);
    });
}

onconnect = function (e) {
// onmessage = function (e) {
    var port = e.ports[0];
    gPort = port;
    sendMsg("xxxxxxxx")
    refresh();
}


function reset() {
    interval = 1 * 6 * 1000;
}

function sendMsg(msg){
    gPort.postMessage(msg);
    // postMessage(msg);
}

async function refresh() {
    if (run) return;
    run = true;
    while (true) {
        await sleep(interval);
        sendMsg("sleep结束");
        let token = await db.getToken();
        sendMsg(token);
        if(!token){
            reset();
            continue;
        }
        fetch("/web992/token/refresh", {
            method: 'POST',
            headers: {
                "Content-Type": "application/json;charset=utf-8",
                'Authorization': token,
            }
        }).then(res => res.json()).then(data => {
            if (data.code == 0) {
                let result = data.data;
                let _token = result.type + " " + result.token;
                db.setToken(_token);
                interval = (result.expires - 1) * 60 * 1000;
            }else{
                reset();
            }
            sendMsg(data);
        }).catch(e => {
            reset();
            sendMsg(e);
        });
    }
}